import {DeleteOutlined, SearchOutlined, UndoOutlined} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Popconfirm, Form, Select, Row, Col, DatePicker, Input } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { createGroup, deleteGroupById, getGroupList, updateGroup } from '@/services/groupManage';
import {
  batchDeleteBlackList,
  deleteBlackList,
  getBlackList,
  getIpLogList,
} from '@/services/ipmanager';
import moment from 'moment';
const { RangePicker } = DatePicker;
const IPAccessRecord: React.FC = () => {
  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    try {
      await createGroup({ ...fields });
      message.success('添加成功！');
      return true;
    } catch (error) {
      message.error('添加失败！' + error.response.data.message);
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: any) => {
    const params = {
      groupDesc: fields.groupDesc,
      groupName: fields.groupName,
      id: fields.id,
    };
    try {
      await updateGroup(params);
      message.success('更新成功！');
      return true;
    } catch (error) {
      message.error('更新失败！' + error.response.data.message);
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除多个节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows) => {
    if (!selectedRows) return true;
    try {
      await batchDeleteBlackList(selectedRows.map((row) => row.id));
      message.success('已删除！');
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    } catch (error) {
      message.error('删除失败！' + error.response.data.message);
      return false;
    }
  };
  const queryData = async () => {
    let values = form.getFieldsValue();
    if (values.dateTime != null && values.dateTime != undefined) {
      values.timeStart = moment(values.dateTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
      values.timeEnd = moment(values.dateTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
    }

    const params = {
      page: page,
      pageSize: pageSize,
    };

    const msg = await getIpLogList(params, values);
    setDataArray(msg.data.ipLogList);
    setPagination({ ...pagination, total: msg.data.total });
  };
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [form] = Form.useForm();
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="IP" name="ip">
                <Input placeholder="请输入IP" onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col span={8}>
              <Form.Item label="操作时间" name="dateTime">
                <RangePicker onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col
              span={12}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >
                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [selectedRows, setSelectedRows] = useState<any[]>();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  useEffect(() => {
    queryData();
  }, [page, pageSize]);

  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  const columns: ProColumns<any>[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'no',
    },
    {
      title: 'IP',
      align: 'center',
      dataIndex: 'ip',
    },
    {
      title: '访问时间',
      align: 'center',
      dataIndex: 'visitTime',
    },
/*    {
      title: '访问路径',
      align: 'center',
      dataIndex: 'path',
    },*/
    // {
    //   title: '内容',
    //   align: 'center',
    //   dataIndex: 'nr',
    // },
    {
      title: '访问设备',
      align: 'center',
      dataIndex: 'device',
    },
    {
      title: '用户操作系统',
      align: 'center',
      dataIndex: 'os',
    },
    {
      title: '浏览器',
      align: 'center',
      dataIndex: 'browser',
    },

    // {
    //   title: '操作',
    //   align: 'left',
    //   dataIndex: 'option',
    //   valueType: 'option',
    //   render: (_, record) => [
    //     <Popconfirm title="确定是否删除?" onConfirm={() => handleRemove([record])} key="delete">
    //       <a style={{ color: 'red' }}>
    //         <DeleteOutlined /> 删除
    //       </a>
    //     </Popconfirm>,
    //   ],
    // },
  ];

  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        // headerTitle="用户列表"
        actionRef={actionRef}
        rowKey={'id'}
        search={false}
        tableStyle={{ textAlign: 'center' }}
        options={false}
        dataSource={dataArray}
        pagination={pagination}
        onChange={handleTableChange}
        toolBarRender={() => [
          // <Button
          //   type="primary"
          //   danger
          //   key="danger"
          //   onClick={() => {
          //     handleRemove(selectedRows);
          //   }}
          // >
          //   <DeleteOutlined />
          //   批量删除
          // </Button>,
        ]}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default IPAccessRecord;
